package cz.muni.fi.pa165.login;

import cz.muni.fi.pa165.enums.AdminRole;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;


/**
 *  Simple authenticator.
 *  
 * @author <a href="mailto:vramik at redhat.com">Vlastislav Ramik</a>,Jakub Janco
 */
@SessionScoped
@Named
public class Authenticator implements Serializable {
    
    private boolean loggedIn;
    private String username;
    private String password;
    
    public boolean isLoggedIn() {
        return loggedIn;
    }

    public boolean isAdmin() {
        return SecurityUtils.getSubject().hasRole(AdminRole.Manager.toString());
    }

    public boolean isDeliveryBoy() {
        return SecurityUtils.getSubject().hasRole(AdminRole.DeliveryBoy.toString());
    }
    
    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    public void login() {
        if (!isLoggedIn()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);

            try {
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
                token.clear();			
                loggedIn = true;
            } catch (Exception ex) {
                loggedIn= false;
            }
        }
    }
    
    public void logout() {
        SecurityUtils.getSubject().logout();
        username = null;
        password = null;
        loggedIn = false;
    }
    
    public String getLoggedUser() {
        
        return SecurityUtils.getSubject().getPrincipal().toString();
    }
}
